<template>
  <div class="app-container" style="padding:0">

    <div class="topLine">
      <!-- 搜索 -->
      <el-form ref="queryForm" :model="listQuery" :inline="true" label-width="68px">
        <el-form-item label="模板名称">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入模板名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="模板类型" >
          <el-select v-model="listQuery.type" placeholder="请选择类型" style="width:100%">
            <el-option
              v-for="item in taskTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增 </el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除 </el-button>
      </div>

    </div>

    <el-table v-loading="loading" :data="list" empty-text="暂无数据" @selection-change="handleSelectionChange">i
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column label="模板名称" align="center" >
        <template slot-scope="scope">
          <div class="nameLine">
            {{ scope.row.name }}<div v-if="scope.row.default_type === 1" class="defaultTag">默认</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="模板描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="班级" align="center" prop="department.name" />
      <el-table-column label="采样时间" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.sampling_interval==5">5秒</div>
          <div v-if="scope.row.sampling_interval==15">15秒</div>
          <div v-if="scope.row.sampling_interval==30">30秒</div>
        </template>
      </el-table-column>
      <el-table-column label="学生画面" align="center" prop="videoStream1" />
      <el-table-column label="老师画面" align="center" prop="videoStream2" />
      <el-table-column label="创建时间" align="center" prop="create_time" :show-overflow-tooltip="true">
        <template slot-scope="scope">{{ scope.row.create_time }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getAllTemplates"
    />

    <!-- 添加或修改 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>

        <el-form-item label="采样时间" prop="sampling_interval">
          <el-select v-model="form.sampling_interval" placeholder="请选择采样时间">
            <el-option
              v-for="item in intervalOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="班级:" prop="department_id">
          <treeselect
            v-model="form.department_id"
            :options="deptOptions"
            :normalizer="normalizer"
            :disable-branch-nodes="true"
            :show-count="true"
            placeholder="请选择班级"
          />
        </el-form-item>

        <el-form-item label="学生画面">
          <el-input v-model="form.videoStream1" placeholder="学生摄像机画面地址" />
        </el-form-item>
        <el-form-item label="老师画面">
          <el-input v-model="form.videoStream2" placeholder="老师摄像机画面地址" />
        </el-form-item>
        
        <el-form-item label="关键字:">
          <div style="display: inline-flex; align-items: center;">
            <el-input
              v-model="inputValue"
              placeholder="请输入关键字"
              size="small"
              style="width: 150px;"
              @keyup.enter.native="handleInputConfirm"
            />
            <el-button
              type="primary"
              size="small"
              style="margin-left: 6px;"
              @click="handleInputConfirm"
            >
              确定
            </el-button>
          </div>
          <div v-if="keywords.length !== 0" class="members-selectedLine">
            <!-- 已添加的 tags -->
            <el-tag
              v-for="(tag, index) in keywords.filter(t => t.trim())"
              :key="index"
              closable
              @close="removeKeyword(index)"
              style="margin-right: 8px"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-form-item>

        <el-form-item label="模板描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="默认模板">
          <el-checkbox  :checked="form.default_type === 1" @change="val => form.default_type = val ? 1 : 0">设为默认模板</el-checkbox>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
// 接口
import { getTemplatesByPage, getTemplateDetail, updateTemplateDetail, addTemplate, deleteTemplate } from '@/api/main'
import { listDept } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'TemplateMain',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 字典表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        type: 1
      },
      taskTypes: [
        { value: 1, label: 'ST教学分析' },
        { value: 2, label: '会议督察' }
      ],
      intervalOptions: [
        { value: 5, label: '5秒' },
        { value: 15, label: '15秒' },
        { value: 30, label: '30秒' }
      ],

      form: {
        type: 1
      },

      // 表单校验
      rules: {
        department_id: [
          { required: true, message: '班级不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        sampling_interval: [
          { required: true, message: '请选择采样时间', trigger: 'change' }
        ]
      },
      // 组织树选项
      deptOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'name'
      },      
      keywords: [], // 标签数组
      inputValue: ''
    }
  },
  watch: {
    // 根据名称筛选组织树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    // this.getList()
    // 获取模板-分页
    this.getAllTemplates()
    // /////////
    this.getTreeselect()
  },
  methods: {

    /** 查询组织下拉树结构 */
    getTreeselect() {
      listDept().then(response => {
        this.deptOptions = response.data
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

    // 获取模板
    getAllTemplates() {
      this.loading = true
      getTemplatesByPage(this.listQuery).then(response => {
        this.list = response.data.template_data
        this.list.forEach(item => {
          if (item.create_time) {
            item.create_time = item.create_time.replace('T', ' ')
          }
        })
        this.total = response.data.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        code: undefined,
        description: undefined,
        department_id: undefined,
        sampling_interval: undefined,
        videoStream1: undefined,
        videoStream2: undefined,
        default_type: 0
      }
      // this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.listQuery.page = 1
      this.getAllTemplates()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
        type: 1
      }
      this.handleQuery()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增模板'
      this.keywords = []
    },

    handleInputConfirm() {
      const value = this.inputValue.trim()
      if (value && !this.keywords.includes(value)) {
        this.keywords.push(value)
      }
      this.inputValue = ''
    },
    removeKeyword(index) {
      this.keywords.splice(index, 1)
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getTemplateDetail(id).then(response => {
        this.open = true
        this.title = '修改模板信息'
        this.form = response.data.template_data
        const str = response.data.template_data.voice_key_words
        this.keywords = str.split('_')
        console.log('----------模板',response)
        console.log('----------this.form',this.form)
      })
    },


    /** 提交按钮 */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id === undefined) {
            // 新增
            this.form.type = 1
            this.form.voice_key_words = this.keywords.join('_')
            addTemplate(this.form).then(response => {
              if (response.code === 20000) {
                this.msgSuccess(response.message)
                this.open = false
                this.getAllTemplates()
                this.keywords = []
              }
            })
          } else {
            // 修改
            this.form.voice_key_words = this.keywords.join('_')
            updateTemplateDetail(this.form).then(response => {
              if (response.code === 20000) {
                this.msgSuccess(response.message)
                this.open = false
                this.getAllTemplates()
                this.keywords = []
              } else {
                this.msgSuccess(response.message)
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return deleteTemplate(ids)
      }).then(() => {
        this.getAllTemplates()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    }
  }
}
</script>

<style>
.topLine{
  padding:20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
}
.el-table .el-table__header-wrapper th{
  background: #e1ecfa;
}
.topLine .el-form-item{
  margin-bottom: 0;
}
.nameLine{
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.defaultTag{
  color: #385eb7;
  font-size: 11px;
  line-height: 18px;
    padding: 0px 6px;
    border: 1px dashed #b2c6e0;
    margin-left: 8px;
    border-radius: 5px;
    background: rgba(231.9, 243.9, 255, 0.4);
}
</style>
